﻿import 'package:getx_scaffold/getx_scaffold.dart';
import 'diet_record_state.dart';
import '../../../core/repository/default_api.dart';
import '../../../entity/energy_balance.dart';
import '../../../services/device_sn_manager.dart';

/// 饮食记录控制器
class DietRecordLogic extends GetxController {
  final DietRecordState state = DietRecordState();

  @override
  void onInit() {
    super.onInit();
    _updateDateText();
    _loadDietData();
  }

  /// 获取设备序列号
  String _getDeviceSn() {
    try {
      final deviceSnManager = Get.find<DeviceSnManager>();
      return deviceSnManager.getDeviceSn();
    } catch (e) {
      print('⚠️ 无法获取DeviceSnManager: $e');
      return '';
    }
  }

  /// 加载饮食数据
  Future<void> _loadDietData() async {
    try {
      state.isLoading.value = true;

      // 获取设备SN
      final deviceSn = _getDeviceSn();

      // 获取当前日期
      final now = DateTime.now();
      String recordDate = '';
      String type = '';

      // 根据选中的时间段设置参数
      switch (state.selectedPeriod.value) {
        case 0: // 日
          recordDate = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
          type = '1';
          break;
        case 1: // 周
          type = '2';
          break;
        case 2: // 月
          type = '3';
          break;
      }

      // 调用能量平衡接口
      final dynamic apiData = await DefaultApi().queryEnergyBalanceGet<dynamic>(
        deviceSn: deviceSn,
        recordDate: recordDate.isNotEmpty ? recordDate : null,
        type: type,
      );

      if (apiData != null && apiData['code'] == 200 && apiData['data'] != null) {
        final balance = EnergyBalance.fromMap(apiData['data'] as Map<String, dynamic>);
        state.energyBalanceData.value = balance;
        
        // 更新状态值
        state.totalCalories.value = (balance.totalFoodKcal ?? 0).toDouble();
        state.activityCalories.value = (balance.totalExerciseKcal ?? 0).toDouble();
        state.energyBalance.value = (balance.energyBalance ?? 0).toDouble();
        

        
        _updateCalorieProgress();
      } else {
        state.energyBalanceData.value = null;
      }

      // 获取饮食记录（柱状图数据）
      final dynamic foodData = await DefaultApi().queryFoodInfoGet<dynamic>(
        deviceSn: deviceSn,
        recordDate: recordDate.isNotEmpty ? recordDate : null,
        type: type,
      );
      if (foodData != null && foodData['code'] == 200 && foodData['data'] != null) {
        final Map<String, dynamic> data = foodData['data'] as Map<String, dynamic>;
        final List<dynamic> list = (data['chartVOList'] as List<dynamic>? ) ?? <dynamic>[];
        final items = list.map((e) {
          final map = e as Map<String, dynamic>;
          final key = (map['key'] ?? '').toString();
          final timeLabel = (map['timeLabel'] ?? '').toString();
          final value = (map['value'] ?? 0);
          final double calories = value is num ? value.toDouble() : double.tryParse(value.toString()) ?? 0.0;
          return FoodBarItem(mealKey: key, timeLabel: timeLabel, calories: calories);
        }).toList();
        state.chartItems.assignAll(items);
        // 更新最大值，预留20%顶部空间
        final double maxVal = items.isEmpty ? 0.0 : items.map((e) => e.calories).reduce((a, b) => a > b ? a : b);
        state.chartMaxY.value = (maxVal * 1.2).clamp(100.0, double.infinity);
        // 绑定摄入总量与目标
        final String? intakeCaloriesStr = data['intakeCalories']?.toString();
        final double intakeTarget = double.tryParse(intakeCaloriesStr ?? '0') ?? 0.0;
        final double consumedCalories = (data['calories'] is num)
            ? (data['calories'] as num).toDouble()
            : double.tryParse('${data['calories']}') ?? 0.0;
        state.targetCalories.value = intakeTarget;
        state.totalCalories.value = consumedCalories;
        _updateCalorieProgress();
      } else {
        state.chartItems.clear();
        state.chartMaxY.value = 0.0;
      }
    } catch (e) {
      print('❌ 加载能量平衡数据失败: $e');
      state.energyBalanceData.value = null;
      state.chartItems.clear();
      state.chartMaxY.value = 0.0;
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 切换时间段（日/周/月）
  void changePeriod(int index) {
    state.selectedPeriod.value = index;
    _updateDateText();
    _loadDietData();
  }

  /// 更新卡路里进度
  void _updateCalorieProgress() {
    if (state.targetCalories.value > 0) {
      state.calorieProgress.value = 
          (state.totalCalories.value / state.targetCalories.value).clamp(0.0, 1.0);
    }
  }

  /// 更新日期文本
  void _updateDateText() {
    final now = DateTime.now();
    switch (state.selectedPeriod.value) {
      case 0: // 日
        state.currentDateText.value = 
            '${now.year}年${now.month}月${now.day}日，星期${_getWeekday(now.weekday)}';
        break;
      case 1: // 周
        state.currentDateText.value = '本周';
        break;
      case 2: // 月
        state.currentDateText.value = '${now.year}年${now.month}月';
        break;
    }
  }

  /// 获取星期几
  String _getWeekday(int weekday) {
    const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
    return weekdays[weekday - 1];
  }

  /// 根据指定日期加载数据
  void loadDataByDate(String recordDate) {
    print('📅 根据日期加载饮食数据: $recordDate');
    
    // 解析日期字符串
    try {
      final parts = recordDate.split('-');
      if (parts.length == 3) {
        final year = int.parse(parts[0]);
        final month = int.parse(parts[1]);
        final day = int.parse(parts[2]);
        final selectedDate = DateTime(year, month, day);
        
        // 更新日期文本
        state.currentDateText.value =
            '$year年$month月$day日，星期${_getWeekday(selectedDate.weekday)}';
        
        // 切换到日视图
        state.selectedPeriod.value = 0;
      }
    } catch (e) {
      print('⚠️ 解析日期失败: $e');
    }

    // 重新加载数据
    _loadDietData();
  }
}
